package com.xlongwei.accounts.dao;

import java.util.Collections;
import java.util.List;

import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Cache;
import org.noear.solon.data.annotation.CacheRemove;
import org.noear.solon.data.annotation.Tran;
import com.xlongwei.accounts.config.MySqlUtils;
import com.xlongwei.accounts.model.Account;

@Component
public class AccountDao {
    @Inject
    MySqlUtils sqlUtils;

    @Tran
    @CacheRemove(keys = "account.${},accounts.${row.userid}")
    public Integer create(Account row) {
        assert row.getAccountid() == null && row.getUserid() != null;
        Object key = sqlUtils.sql("insert into t_account(type,name,userid) values(?,?,?)",
                row.getType(), row.getName(), row.getUserid()).updateReturnKey();
        return Integer.parseInt(key.toString());
    }

    @Cache(key = "account.${accountid}")
    public Account retrieve(Integer accountid) {
        return sqlUtils.sql("select accountid,type,name,userid from t_account where accountid=?", accountid)
                .queryRow(Account.class);
    }

    @Tran
    @CacheRemove(keys = "account.${row.accountid},accounts.${row.userid}")
    public Integer update(Account row) {
        assert row.getAccountid() != null;
        return sqlUtils.sql("update t_account set name=? where accountid=?", row.getName(),
                row.getAccountid()).update();
    }

    @Cache(key = "accounts.${userid}")
    public List<Account> list(Integer userid) {
        List<Account> list = sqlUtils
                .sql("select accountid,type,name,userid from t_account where userid=0 or userid=? order by type,accountid",
                        userid)
                .queryRowList(Account.class);
        return list != null ? list : Collections.emptyList();
    }
}
